    //
//  ScoreViewController.m
//  Quiz
//
//  Created by AnhLH-Oriolus on 31/07/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ScoreViewController.h"
#import "countryquizAppDelegate.h"
#import "MainController.h"

@implementation ScoreViewController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
-(id)init{
	self = [super init];
	//[self loadData];
	return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[v setImage:[UIImage imageNamed:@"images/backGround.png"]];
	[v setUserInteractionEnabled:YES];
	self.view = v;
	[v release];
	
	UIImageView *vBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
	[vBar setImage:[UIImage imageNamed:@"images/bar.png"]];
	[vBar setUserInteractionEnabled:YES];
	[self.view addSubview:vBar];
	[vBar release];
	
	UIImage * img = [UIImage imageNamed:@"images/home_btn.png"];
	UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];
	[btnBack setBackgroundColor:[UIColor clearColor]];
	[btnBack setImage:img forState:UIControlStateNormal];
	[btnBack addTarget:nil action:@selector(backToMenu) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnBack];
	[btnBack release];
	
	//UILabel *titleScore = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 100, 50)];
//	[titleScore setBackgroundColor:[UIColor clearColor]];
//	titleScore.textAlignment = UITextAlignmentCenter;
//	titleScore.textColor = [UIColor whiteColor];
//	titleScore.font = [UIFont fontWithName:@"Arial" size:30];
//	titleScore.text = @"Score";
//	[self.view addSubview:titleScore];
//	[titleScore release];
	
	FontLabel *titleScore = [[FontLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 50) fontName:@"scoreboard" pointSize:30];
	[titleScore setBackgroundColor:[UIColor clearColor]];
	titleScore.textAlignment = UITextAlignmentCenter;
	titleScore.textColor = [UIColor colorWithRed:243 green:255 blue:62 alpha:1.0];
	titleScore.text = @"Score";
	[self.view addSubview:titleScore];
	[titleScore release];
	
	ownScore = [[OwnScoreView alloc] initWithFrame:CGRectMake(0, 50, 300, 200)];
	[ownScore setLabelTitle:0];
	[self.view addSubview:ownScore];
	[ownScore release];
	
	img = [UIImage imageNamed:@"images/topScore.png"];
	btnUpdateScore = [[UIButton alloc] initWithFrame:CGRectMake(320-40-5, 5, 40, 40)];
	[btnUpdateScore setBackgroundColor:[UIColor clearColor]];
	[btnUpdateScore setImage:img forState:UIControlStateNormal];
	[btnUpdateScore addTarget:nil action:@selector(updateScore) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:btnUpdateScore];
	[btnUpdateScore release];
	
	multiPlayerScore = [[OwnScoreView alloc] initWithFrame:CGRectMake(0, 240, 300, 220)];
	[multiPlayerScore setLabelTitle:1];
	[self.view addSubview:multiPlayerScore];
	[multiPlayerScore release];
}

-(void)backToMenu{
	[self.view removeFromSuperview];
	[g_AppDelegate.mainCtrl openMenuViewCtrl];
}

-(void)updateScore{
	if(isUpdate)
		return;
	
	UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Update to Multiplayer's score?" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel",nil];
	[al show];
	[al release];
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 0){
		NSLog(@"0k");
		//update score
		isUpdate = TRUE;
		[self updateMulScore];
		[multiPlayerScore setDataWithPlayerName:arrMulPlayer withArrScore:arrMulScore];
	}
	if(buttonIndex == 1){
		NSLog(@"cancel");
	}
}

-(void)loadViewWithMode:(int)mode{
	if(mode == 0){//only view
		btnUpdateScore.hidden = YES;
	}else {
		isUpdate = FALSE;
		btnUpdateScore.hidden = NO;
	}
	
	[self loadData];
	[ownScore setDataWithPlayerName:arrOwnPlayer withArrScore:arrOwnScore];
	[multiPlayerScore setDataWithPlayerName:arrMulPlayer withArrScore:arrMulScore];

}

-(BOOL)openDb{
	NSString *path = [NSString stringWithFormat:@"%@/FootballTeam.db",g_strMainBundlePath];
	db = [FMDatabase databaseWithPath:path];
    if (![db open]) {
        NSLog(@"Could not open db.");
		return FALSE;
    }
	NSLog(@"DB opened successfully");
	return TRUE;
}

//lay du lieu cho mode 0 get own data
//			   va mode 1 get mul data
-(void)loadData{
	if(arrOwnPlayer){
		[arrOwnPlayer removeAllObjects];
	}else {
		arrOwnPlayer = [[NSMutableArray alloc] init];
	}
	if(arrOwnScore){
		[arrOwnScore removeAllObjects];
	}else {
		arrOwnScore = [[NSMutableArray alloc] init];
	}
	if(arrMulPlayer){
		[arrMulPlayer removeAllObjects];
	}else {
		arrMulPlayer = [[NSMutableArray alloc] init];
	}
	if(arrMulScore){
		[arrMulScore removeAllObjects];
	}else {
		arrMulScore = [[NSMutableArray alloc] init];
	}
	
	if([self openDb]){
		NSString *sql = [NSString stringWithFormat:@"Select PlayerName, Score From Player, Score Where Player.PlayerID = Score.PLayerID and PlayerName like \'%@\' and Score.Mode = 0 ORDER BY Score.Score DESC LIMIT 10",sName];
		//NSLog(@"%@", player);
		//get name, score of own player
		FMResultSet *rs = [db executeQuery:sql];	
		while([rs next])
		{
			NSString *name = [rs stringForColumn:@"PlayerName"];
			int score = [rs intForColumn:@"Score"];
			NSLog(@"%@ - %d", name, score);
			[arrOwnPlayer addObject:name];
			[arrOwnScore addObject:[NSNumber numberWithInt:score]];
		}
		[rs close];
		
		sql = @"Select PlayerName, Score From Player, Score Where Player.PlayerID = Score.PLayerID and Score.Mode = 1 ORDER BY Score.Score DESC LIMIT 100";
		rs = [db executeQuery:sql];	
		while([rs next])
		{
			NSString *name = [rs stringForColumn:@"PlayerName"];
			int score = [rs intForColumn:@"Score"];
			NSLog(@"%@ - %d", name, score);
			[arrMulPlayer addObject:name];
			[arrMulScore addObject:[NSNumber numberWithInt:score]];
		}
		[rs close];
		
		[self closeDb];
	}else {
		NSLog(@"Cannot open database");
	}
}

-(void)closeDb{
    if (db && [db open]) {
		[db close];
    }
}


-(void)willUpdateWithPlayer:(NSString *)playerName andScore:(int)score{
	if(!player){
		player = [[NSString alloc] initWithString:playerName];
	}
	player = [NSString stringWithFormat:@"%@",playerName];
	iScore = score;
}

-(void)updateMulScore{
	if ([self openDb]) {
		int total=0;
		int index = -1;
		NSString *sql1 = [NSString stringWithFormat:@"select count(Score) as Total From Score where Score > %d and Mode = 1 ORDER BY Score Desc" , iScore];

		FMResultSet *rs = [db executeQuery:sql1];	
		while([rs next])
		{
			total = [rs intForColumn:@"Total"];
			break;
		}
		[rs close];
		
		if(total < 100){
			NSString *sql = [NSString stringWithFormat:@"select PlayerID from Player where PlayerName like \'%@\'",sName];
			//NSLog(@"ten %@", sql);
			rs = [db executeQuery:sql];
			while( [rs next])
			{
				index = [rs intForColumn:@"PlayerID"];
				break;
			}
			//NSLog(@"id %d", index);
			[rs close];
			
			int iTotalScore = 0;
			rs = [db executeQuery:@"select max(ScoreID) as Total from Score"];	
			while([rs next])
			{
				iTotalScore = [rs intForColumn:@"Total"];
				break;
			}
			[rs close];
			
			if(index == -1){
				[self closeDb];
				return;
			}
			
			sql = [NSString stringWithFormat:@"insert into Score values(1,%d,%d,%d)", index, iScore, iTotalScore+1];
			[db beginTransaction];
			[db executeUpdate:sql];
			[db commit];
		}
		[self closeDb];
	}
	
	[self loadData];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
